package com.mh.mq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.util.List;

/**
 * @author 马浩 1085473391@qq.com
 * @Package com.mh.mq
 * @Description: TODO ( 消费者 )
 * @Date 2018/12/28 15:38
 * @Version V1.0
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        consumer2();
    }

    public static void consumer1() throws Exception{
        //
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("demo-topic");
        //nameserver地址
        consumer.setNamesrvAddr("localhost:9876");
        /**
         * 默认情况下不需要设置instanceName，rocketmq会使用ip@pid作为instanceName(pid代表jvm名字)
         * 如果设置instanceName，rocketmq会使用ip@instanceName作为consumer的唯一标示，此时需要注意instanceName需要不同。
         */
        consumer.setInstanceName("rmq-instance");
        //
        consumer.subscribe("test", "demo-tag");


        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(
                    List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println(new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("Consumer Started.");
    }

    public static void consumer2() throws Exception{
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("demo-topic");

        consumer.setNamesrvAddr("localhost:9876");
//        consumer.setInstanceName("rmq-instance");
        consumer.subscribe("test", "TagA");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(
                    List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println(new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("Consumer Started.");
    }


}
